package exttable.formgenerator;

import dbutils.DbUtils;
import dbutils.StoredQueries;
import exttable.testfiller.formcomponents.EInputComponents;
import exttable.userdefineextendsclasses.UserDefineJMenu;
import exttable.userdefineextendsclasses.UserDefineJMenuItem;
import utils.Localisation;

import javax.swing.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by IntelliJ IDEA.
 * User: ADMIN
 * Date: 08.07.2010
 * Time: 15:29:49
 * To change this template use File | Settings | File Templates.
 */
public class ComponentsToPanel {


    final static Map<String, EFillValuesToVectorFromComponents> mapCLasses = new HashMap<String, EFillValuesToVectorFromComponents>();

    public static Vector<Vector> returnRowData(String tableName, Component[] compArray, Vector<String> nameOfColumnForInsert, Vector<Object> valueOfColumnForInsert, Vector<Vector> rowData) throws Exception {


        for (Component aCompArray : compArray) {
            if (aCompArray instanceof JLabel || aCompArray instanceof JButton) {
                continue;
            } else if (aCompArray instanceof JPanel) {
                JPanel tempPanel = (JPanel) aCompArray;
                if (tempPanel.getComponent(0).getClass().getSimpleName().equals("JButton")) {
                    continue;
                }
            }
            Vector<Object> valueVector = new Vector<Object>();
            Connection conn = DbUtils.getDBConnectionGeneral();
            valueVector.add(TranslateFields.getTranslateOfColumnOrOfTable("additional_columns", "column_name", aCompArray.getName(), conn));
            if (aCompArray.getName() != null) {
                nameOfColumnForInsert.add(aCompArray.getName());
            }
            EFillValuesToVectorFromComponents.valueOf(mapCLasses.get(aCompArray.getClass().getSimpleName()).toString()).caseDependenceFromClass(aCompArray, valueVector, valueOfColumnForInsert);
            rowData.add(valueVector);
        }

        return rowData;
    }


    public static int addComponentsFromDB(JPanel panel, String tableName, Object obj) {
        int insertBySystem = 0;
        try {
            PreparedStatement ps;
            Connection conn = DbUtils.getDBConnectionGeneral();
            ps = conn.prepareStatement(StoredQueries.getQuery(StoredQueries.CASES_FROM_INFORMATION_SCHEMA));
            ps.setString(1, DbUtils.GENERAL_DATABASE_NAME);
            ps.setString(2, tableName);
            ps.setString(3, DbUtils.GENERAL_DATABASE_NAME);
            ps.setString(4, tableName);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                if (rs.getString("FIELD_TYPE").equals("SKIP_ELEMENT")) {
                    insertBySystem = 1;
                    continue;
                } else if (rs.getString("FIELD_TYPE").equals("AUTO_INCREMENT")) {
                    continue;
                }
                panel.add(EInputComponents.valueOf("J_LABEL").getComponent(rs, null, null));
                panel.add(EInputComponents.valueOf(rs.getString("FIELD_TYPE")).getComponent(rs, null, obj));
            }
            conn.close();
        } catch (Exception exp) {
            exp.printStackTrace();
        }
        return insertBySystem;
    }

    public static JMenu createDicMenu() {
        UserDefineJMenu dictionaries = new UserDefineJMenu(Localisation.getMessage("menu.dictionaries"),3);
        try {
            PreparedStatement ps;
            Connection conn = DbUtils.getDBConnectionGeneral();
            ps = conn.prepareStatement("");
            ResultSet rs = ps.executeQuery("select dic_name from editables_dics where is_ediatable=1");
            while (rs.next()) {
                UserDefineJMenu dicName = new UserDefineJMenu(TranslateFields.getTranslateOfColumnOrOfTable("table_traslation_list", "table_name", rs.getString("dic_name"), conn),1);
                dicName.setName(rs.getString("dic_name"));

                UserDefineJMenuItem addDictionary = new UserDefineJMenuItem(Localisation.getMessage("menuItem.add"),2);
                addDictionary.setName(rs.getString("dic_name"));
                addDictionary.addActionListener(ListenerFactory.generateViewAndInsertForm());
                dicName.add(addDictionary);
                dictionaries.add(dicName);

            }
            conn.close();
        } catch (Exception excep) {
            excep.printStackTrace();
        }

        return dictionaries;
    }

    static {
        mapCLasses.put(JLabel.class.getSimpleName(), EFillValuesToVectorFromComponents.SKIP_ELEMENT);
        mapCLasses.put(JButton.class.getSimpleName(), EFillValuesToVectorFromComponents.SKIP_ELEMENT);
        mapCLasses.put(JTextField.class.getSimpleName(), EFillValuesToVectorFromComponents.INPUT_TEXT);
        mapCLasses.put(JFormattedTextField.class.getSimpleName(), EFillValuesToVectorFromComponents.FORMATTED_TEXT_FIELD);
        mapCLasses.put(JTextArea.class.getSimpleName(), EFillValuesToVectorFromComponents.TEXT_AREA);
        mapCLasses.put(JComboBox.class.getSimpleName(), EFillValuesToVectorFromComponents.SELECT_ONE_MENU);
        mapCLasses.put(JPanel.class.getSimpleName(), EFillValuesToVectorFromComponents.PANEL);
    }

    public static InputVerifier setNumberValidator() {
        return new InputVerifier() {
            @Override
            public boolean verify(JComponent comp) {
                JTextField textField = (JTextField) comp;
                try {
                    Integer.parseInt(textField.getText());
                    return true;
                } catch (NumberFormatException e) {
                    Toolkit.getDefaultToolkit().beep();

                    if (textField.getText().trim().length() < 1) {
                        JOptionPane.showMessageDialog(null, Localisation.getMessage("error.nodata"),
                                Localisation.getMessage("warring.waring"), JOptionPane.WARNING_MESSAGE);
                    } else if (textField.getText().getClass().getSimpleName().equals("String")) {
                        JOptionPane.showMessageDialog(null, Localisation.getMessage("error.testentered"),
                                Localisation.getMessage("warring.waring"), JOptionPane.WARNING_MESSAGE);
                        textField.setText("");
                    }
                }
                return false;
            }
        };
    }

    public static InputVerifier setDoubleValidator() {
        return new InputVerifier() {
            @Override
            public boolean verify(JComponent comp) {
                JTextField textField = (JTextField) comp;
                try {
                    Double.parseDouble(textField.getText().replace(",", "."));
                    return true;
                } catch (NumberFormatException e) {
                    Toolkit.getDefaultToolkit().beep();

                    if (textField.getText().trim().length() < 1) {
                        JOptionPane.showMessageDialog(null, Localisation.getMessage("error.nodata"),
                                Localisation.getMessage("warring.waring"), JOptionPane.WARNING_MESSAGE);
                    } else if (textField.getText().getClass().getSimpleName().equals("String")) {
                        JOptionPane.showMessageDialog(null, Localisation.getMessage("error.testentered"),
                                Localisation.getMessage("warring.waring"), JOptionPane.WARNING_MESSAGE);
                        textField.setText("");
                    }
                }
                return false;
            }
        };
    }

    public static InputVerifier setEmailValidator() {
        return new InputVerifier() {
            @Override
            public boolean verify(JComponent comp) {
                JTextField emailField = (JTextField) comp;
//             if(emailField.getText().trim().length()<1){
//                JOptionPane.showMessageDialog(null, Localisation.getMessage("error.nodata"),
//                                Localisation.getMessage("warring.waring"),JOptionPane.WARNING_MESSAGE);
//                 return false;
//             }
                if (emailField.getText().trim().length() < 1) {
                    int YES = 0;
                    Object[] options = {Localisation.getMessage("form.yes"), Localisation.getMessage("form.no")};

                    int choice = JOptionPane.showOptionDialog(null
                            , Localisation.getMessage("warring.wantemptyfield")
                            , Localisation.getMessage("warring.waring")
                            , JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
                    return choice == YES;
                }
                return isEmailValid(emailField);
            }
        };
    }

    public static boolean isEmailValid(JTextField emailField) {
        Pattern p = Pattern.compile("^www\\.");
        Matcher m = p.matcher(emailField.getText());
        String sDomen = "[a-z][a-z0-9_.-]*[\\w]";
        String sDomen2 = "[a-z0-9]+";
        String sDomen3 = "([a-z]){2,4}";
        Pattern p2 = Pattern.compile(sDomen + "@" + sDomen2 + "[.]" + sDomen3);
        Matcher m2 = p2.matcher(emailField.getText().toLowerCase());
        if (!m.find()) {
            if (m2.matches()) {
                return true;
            }
        }
        JOptionPane.showMessageDialog(null, Localisation.getMessage("error.email"),
                Localisation.getMessage("warring.waring"), JOptionPane.WARNING_MESSAGE);

//        emailField.setText("");
        return false;

    }

    public static InputVerifier setVolunteerCodeValidator() {
        return new InputVerifier() {
            @Override
            public boolean verify(JComponent comp) {
                JTextField textField = (JTextField) comp;
                if (textField.getText().trim().length() < 1) {
                    Toolkit.getDefaultToolkit().beep();
                    JOptionPane.showMessageDialog(null, Localisation.getMessage("error.nodata"),
                            Localisation.getMessage("warring.waring"), JOptionPane.WARNING_MESSAGE);
                    return false;
                } else if (textField.getText().trim().length() != 4) {
                    Toolkit.getDefaultToolkit().beep();
                    JOptionPane.showMessageDialog(null, Localisation.getMessage("error.lenthvolunteercode"),
                            Localisation.getMessage("warring.waring"),
                            JOptionPane.WARNING_MESSAGE);
                    return false;

                } else if (!ComponentsToPanel.isEnglishCharacter(textField.getText().trim().charAt(0))) {
                    Toolkit.getDefaultToolkit().beep();
                    JOptionPane.showMessageDialog(null, Localisation.getMessage("form.firstLatinSmallLetter"),
                            Localisation.getMessage("warring.waring"),
                            JOptionPane.WARNING_MESSAGE);
                    return false;


                }
                return true;
            }
        };
    }

    public static String getDuplicateMessage(String str) {
        Pattern p = Pattern.compile("'.+?'");
        Matcher m = p.matcher(str);
        List<String> valueColumnName = new ArrayList<String>();
        while (m.find()) {
            valueColumnName.add(m.group());
        }
        return Localisation.getMessage("table.column.prameter") + " " +
                valueColumnName.get(0) + " " + Localisation.getMessage("table.columnfor") + " " +
                valueColumnName.get(1) + " " +
                Localisation.getMessage("message.presentindb");
    }

    public static boolean isEnglishCharacter(Character ch) {
        Map<Character, Integer> latinSmallLetter = new HashMap<Character, Integer>();
        latinSmallLetter.put('a', 97);
        latinSmallLetter.put('b', 98);
        latinSmallLetter.put('c', 99);
        latinSmallLetter.put('d', 100);
        latinSmallLetter.put('e', 101);
        latinSmallLetter.put('f', 102);
        latinSmallLetter.put('g', 103);
        latinSmallLetter.put('h', 104);
        latinSmallLetter.put('i', 105);
        latinSmallLetter.put('j', 106);
        latinSmallLetter.put('k', 107);
        latinSmallLetter.put('l', 108);
        latinSmallLetter.put('m', 109);
        latinSmallLetter.put('n', 110);
        latinSmallLetter.put('o', 111);
        latinSmallLetter.put('p', 112);
        latinSmallLetter.put('q', 113);
        latinSmallLetter.put('r', 114);
        latinSmallLetter.put('s', 115);
        latinSmallLetter.put('t', 116);
        latinSmallLetter.put('u', 117);
        latinSmallLetter.put('v', 118);
        latinSmallLetter.put('w', 119);
        latinSmallLetter.put('x', 120);
        latinSmallLetter.put('y', 121);
        latinSmallLetter.put('z', 122);

        return latinSmallLetter.get(ch) != null;
    }

    public static List<String> getListSubFields(String tableName, String tableField, String value) {
        List<String> toReturn = new ArrayList<String>();
        String query = "SELECT list_subfields " +
                " FROM dic_general" +
                " WHERE " +
                " table_name='" + tableName + "' " +
                " AND table_field='" + tableField + "' " +
                " AND name_ru='" + value + "'";
        try {
            Connection conn = DbUtils.getDBConnectionGeneral();
            PreparedStatement ps = conn.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                if (rs.getString("list_subfields") == null) {
                    continue;
                }
                String[] arrayStr = rs.getString("list_subfields").split(",");
                Collections.addAll(toReturn, arrayStr);
            }
            ps.close();
            conn.close();
        } catch (Exception exp) {
            exp.printStackTrace();
        }
        return toReturn;
    }

    public static boolean isHaveSubFields(String tableName, String tableField) {
        boolean toReturn = false;
        String query = "SELECT list_subfields " +
                " FROM dic_general" +
                " WHERE " +
                " table_name='" + tableName + "' " +
                " AND table_field='" + tableField + "' ";
        try {
            Connection conn = DbUtils.getDBConnectionGeneral();
            PreparedStatement ps = conn.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                if (rs.getString("list_subfields") != null) {
                    toReturn = true;
                }
            }
        } catch (Exception exp) {
            exp.printStackTrace();
        }

        return toReturn;
    }
}
